package com.letoo.sso.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;

import com.letoo.sso.common.exception.BusinessException;

/**
 * MD5消息摘要的工具类
 * 
 * @author dengjie
 *
 */
public class MD5Utils {

    private static final String CHARSET = "UTF8";

    private static final String ALG = "MD5";

    public static String encrypt(String str) {
        byte[] digest = null;
        try {
            digest = DigestPass.digest(ALG, str.getBytes(CHARSET));
        } catch (NoSuchAlgorithmException e) {
            throw new BusinessException(e);
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(e);
        }
        return encode(digest);
    }

    public static String encryptWithKey(String str, String key) {
        byte[] digest = null;
        try {
            digest = DigestPass.digest(ALG, str.getBytes(CHARSET), key.getBytes(CHARSET));
        } catch (NoSuchAlgorithmException e) {
            throw new BusinessException(e);
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(e);
        }
        return encode(digest);
    }

    public static String encode(byte[] plain) {
        return new String(Base64.encodeBase64(plain));
    }

    /***
     * MD5加码 生成32位md5码
     * 
     * @param inStr
     *            被摘要字符串
     */
    public static String string2MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    /**
     * 将字符串中的中文转成unicode
     * 
     * @param s
     *            转unicode
     * @return 转后的字符串
     */
    public static String toUnicodeString(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                sb.append("\\u" + Integer.toHexString(c));
            }
        }
        return sb.toString();
    }

    /**
     * 判断是否为中文字符
     * 
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 对指定字符串进行MD5后进行BASE64.该方法用于密码注册加密。客户端也是同样的算法。
     * 
     * @param str
     *            指定字符串
     * @return 结果字符串
     */
    public static String md5AndBase64(String str) {
        return encode(string2MD5(str).getBytes());
    }

    public static void main(String[] args) {
        System.out.println(md5AndBase64("yeyuxuanshou"));
    }
}

class DigestPass {
    /**
     * 
     * @param alg
     *            String 算法，通常为MD5,SHA
     * @param plainByte
     *            byte[] 明文的二进制
     * @return byte[] 二进制的消息摘要
     * @throws NoSuchAlgorithmException
     */
    public static byte[] digest(String alg, byte[] plainByte) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(alg);
        md.update(plainByte);
        return md.digest();
    }

    public static byte[] digest(String alg, byte[] plainByte, byte[] key) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(alg);
        md.update(plainByte);
        return md.digest(key);
    }
}
